package com.heima.search.service.impl;

import com.heima.common.consatnts.search.SearchConstants;
import com.heima.common.exception.CustException;
import com.heima.es.service.EsService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDTO;
import com.heima.model.search.vos.SearchArticleVO;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.jsoup.helper.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * author by itheima
 *
 * @Date 2022/3/15
 * Description
 */
@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {
    @Autowired
    EsService<SearchArticleVO> esService;

    @Autowired
    ApUserSearchService apUserSearchService;
    @Value("${file.minio.readPath}")
    String readPath;
    @Value("${file.oss.web-site}")
    String webSite;
    @Override
    public ResponseResult search(UserSearchDTO dto) {
        // 1. 检查参数   (关键字)
            if(StringUtil.isBlank(dto.getSearchWords())){
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"搜索的关键词不能为空");
            }
            if(dto.getMinBehotTime()==null){
                dto.setMinBehotTime(new Date());
            }
        ApUser user = AppThreadLocalUtils.getUser();
            if(user!=null){
                // 因为 插入历史记录的方法是异步执行的，这里提前获取登陆用户id
                dto.setEntryId(user.getId());
                //异步调用保存用户输入关键词记录
                apUserSearchService.insert(dto);
            }
        // 异步保存历史记录
        apUserSearchService.insert(dto);
        // 2. 封装查询参数
        SearchSourceBuilder sourceBuilderr= new SearchSourceBuilder();
        // 2.1  创建bool条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 2.2   关键词  match ==> title
        boolQuery.must(QueryBuilders.matchQuery("title",dto.getSearchWords()));
        // 2.3   时间    range ==> publishTime
        boolQuery.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));
        sourceBuilderr.query(boolQuery);
        // 2.4   排序条件   publishTime  降序
        sourceBuilderr.sort("publishTime", SortOrder.DESC);
        // 2.5   分页条件    size
        sourceBuilderr.from(0);
        sourceBuilderr.size(dto.getPageSize());
        // 2.6   高亮条件  (哪个字段   前置标签   后置标签)
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        highlightBuilder.postTags("</font>");
        highlightBuilder.field("title");
        sourceBuilderr.highlighter(highlightBuilder);
        // 3 执行搜索
        PageResponseResult result = esService.search(sourceBuilderr, SearchArticleVO.class, SearchConstants.ARTICLE_INDEX_NAME);
        // 4. 在返回结果中添加静态页的前缀路径
       List<SearchArticleVO> list= (List<SearchArticleVO>) result.getData();
        for (SearchArticleVO searchArticleVO : list) {
            searchArticleVO.setStaticUrl(readPath+searchArticleVO.getStaticUrl());
            String images = searchArticleVO.getImages();
            if(StringUtils.isNotBlank(images)){
                images= Arrays.stream(images.split(","))
                        .map(url->webSite+url)
                        .collect(Collectors.joining(","));
                searchArticleVO.setImages(images);
            }
        }
        return result;
    }

    @Override
    public void saveArticle(SearchArticleVO article) {
        esService.save(article,SearchConstants.ARTICLE_INDEX_NAME);
    }

    @Override
    public void deleteArticle(String articleId) {
        esService.deleteById(articleId,SearchConstants.ARTICLE_INDEX_NAME);
    }
}
